<template>
  <div class="users-base-wrapper">
    <!-- 主要部分 -->
    <main class="user_main_part">
      <!-- 💭筛选框 -->
      <section class="users_input">
        <el-form
          ref="formRef"
          :model="formData"
          label-width="150px"
          style="width: 90%; margin: 0 auto; text-align: center"
        >
          <el-row>
            <el-col v-for="item in formColumns" :key="item.prop" :span="8">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-input
                  v-if="item.ele === 'input'"
                  v-model="formData[item.prop]"
                  size="mini"
                  style="width: 90%"
                  maxlength="30"
                  placeholder="请输入"
                  clearable
                ></el-input>
                <el-select
                  v-if="item.ele === 'select'"
                  v-model="formData[item.prop]"
                  size="mini"
                  clearable
                  style="width: 90%"
                  maxlength="30"
                >
                  <el-option v-for="it in item.options" :key="it.value" :value="it.value" :label="it.label">{{
                    it.label
                  }}</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </section>
      <!-- 💭操作按钮 -->
      <section class="users_button">
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
          <el-button size="mini" @click="handleClear">重置</el-button>
          <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
          <el-button size="mini" @click="handleDownLoadData()">导出</el-button>
          <column-control
            v-model="tableColumns"
            size="mini"
            style="margin-left: 8px; margin-right: 8px; float: right"
          ></column-control>
        </el-row>
      </section>
      <!-- 💭表格部分 -->
      <section class="users_table">
        <!-- 表格 -->
        <el-table :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :data="tableData" :stripe="true">
          <template v-for="(column, index) in tableColumns">
            <el-table-column v-if="column.visible" :key="index" :label="column.name" align="center">
              <template v-slot="{ row }">
                <div v-if="column.key === 'status'">
                  <el-tag v-if="row.status === 0" type="warning">未激活</el-tag>
                  <el-tag v-if="row.status === 1" type="success">激活</el-tag>
                  <el-tag v-if="row.status === 2" type="danger">禁用</el-tag>
                </div>
                <div v-else-if="column.key === 'roleList'">
                  <span v-for="item in row.roleList" :key="item.id">
                    {{ item.name + '（' + item.code + '）' }}
                  </span>
                </div>
                <div v-else-if="column.key === 'isStatus'">
                  <el-switch
                    v-model="row.status"
                    active-color="#13ce66"
                    :active-value="1"
                    :inactive-value="2"
                    @change="handleSwitchChange($event, row)"
                  >
                  </el-switch>
                </div>
                <div v-else>
                  {{ row[column.key] }}
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" align="center" min-width="180px">
            <template v-slot="{ row }">
              <el-button type="text" @click="handleEdit(row)">修改</el-button>
              <el-button type="text" @click="handleRenew(row)">重发邮件</el-button>
              <el-button type="text" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="end" style="height: 60px" align="middle">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.pageNo"
            :page-sizes="[10, 20, 50]"
            :page-size="pageParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageParams.total"
          >
          </el-pagination>
        </el-row>
      </section>
    </main>
    <!-- 新增框 -->
    <UsersAddDia
      ref="UsersAddDia"
      :projectId="projectId"
      :addVis.sync="addVis"
      :roleOptions="roleOptions"
      @createUserData="createUserData"
    >
    </UsersAddDia>
    <!-- 编辑框 -->
    <UsersEditDia
      ref="UsersEditDia"
      :projectId="projectId"
      :editVis.sync="editVis"
      :editDataProp="editDataProp"
      :roleOptions="roleOptions"
      @updateUserData="updateUserData"
    ></UsersEditDia>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import UsersAddDia from './components/UsersAddDia.vue'
import UsersEditDia from './components/UsersEditDia.vue'
import { handleExportResponse } from '@/utils/index'
export default {
  name: 'users-manage',
  components: {
    UsersAddDia,
    UsersEditDia,
  },
  data() {
    return {
      // 表单规则
      formColumns: [
        { ele: 'input', label: '姓名：', prop: 'username' },
        { ele: 'input', label: '邮箱：', prop: 'email' },
        { ele: 'input', label: '单位：', prop: 'orgName' },
        {
          ele: 'select',
          label: '账号状态：',
          prop: 'status',
          options: [
            { value: '0', label: '未激活' },
            { value: '1', label: '激活' },
            { value: '2', label: '禁用' },
          ],
        },
        {
          ele: 'select',
          label: '角色：',
          prop: 'roleId',
          options: [],
        },
      ],
      // 表单数据
      formData: {
        username: '',
        email: '',
        orgName: '',
        status: '',
        roleId: '',
      },
      // 表格数据
      tableData: [],
      addVis: false,
      editVis: false,
      editDataProp: {},
      pageParams: {
        total: 0,
        pageNo: 1,
        pageSize: 10,
      },
      projectId: '',
      tableColumns: [
        { name: '姓名', key: 'nickname', visible: true },
        { name: '电话', key: 'mobile', visible: true },
        { name: '邮箱', key: 'email', visible: true },
        { name: '所属单位', key: 'orgName', visible: true },
        { name: '角色', key: 'roleList', visible: true },
        { name: '状态', key: 'status', visible: true },
        { name: '是否启用', key: 'isStatus', visible: true },
        { name: '最近登录系统时间', key: 'loginTime', visible: true },
        { name: '最近进入项目时间', key: 'loginProjectTime', visible: true },
      ],
      roleOptions: [],
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.getUserData()
    this.getRoleData()
  },
  mounted() {},

  methods: {
    ...mapActions('usersManage', [
      'updateUserDataAPI', // 修改信息
      'createUserDataAPI', // 新增用户
    ]),
    ...mapActions('roleManage', ['getRoleDataAPI']), // 增加projectId
    ...mapActions('projectPersonRoleManage', [
      'getTableDataAPI',
      'addProjectPersonAPI',
      'removeProjectPersonAPI',
      'recordLoginProjectAPI',
      'exportProjectPersonAPI',
    ]),


    // 获取角色
    getRoleData() {
      const params = {
        projectId: this.projectId,
        pageNo: 1,
        pageSize: 1000,
      }
      this.getRoleDataAPI({ params }).then(res => {
        this.roleOptions = res.data.records
        const arr = res.data.records.map(item => {
          return {
            label: item.name,
            value: item.id,
          }
        })
        this.formColumns[4].options = arr
      })
    },
    // 获取表格数据
    async getUserData() {
      const params = {
        ...this.formData,
        ...this.pageParams,
        projectId: this.projectId,
      }
      this.getTableDataAPI({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.pageParams.total = data.total
          this.tableData = data.records
          this.tableData.isStatus = this.tableData.status
        }
      })
    },

    handleEdit(row) {
      this.editVis = true
      this.editDataProp = { ...row }
    },
    // 点击重发
    handleRenew(row) {
      this.$message.warning('功能开发中！')
    },
    // 点击删除
    handleDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 用户点击了确定按钮，执行相应的操作
          const data = {
            userIds: [row.id],
            projectId: this.projectId,
          }
          this.removeProjectPersonAPI({ data }).then(res => {
            const { code } = res
            if (code === 200) {
              this.$message.success('删除成功')
              const pageLastOne =
                this.pageParams.total % this.pageParams.pageSize === 1 &&
                Math.floor(this.pageParams.total / this.pageParams.pageSize) === this.pageParams.pageNo - 1
              if (pageLastOne) {
                if (this.pageParams.pageNo !== 1) {
                  this.pageParams.pageNo = this.pageParams.pageNo - 1
                }
              }
              this.getUserData()
            }
          })
        })
        .catch(() => {})
    },
    handleSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.pageParams.total = 0
      this.getUserData()
    },
    handleClear() {
      this.$refs.formRef.resetFields()
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.pageParams.total = 0
      this.getUserData()
    },
    handleAdd() {
      this.addVis = true
    },
    handleDownLoadData() {
      const data = {
        projectDatabaseId: this.projectDatabaseId,
        projectId: this.projectId,
      }
      this.exportProjectPersonAPI({ data }).then(res => {
        const { data } = res
        handleExportResponse(data, '项目成员_列表')
      })
    },
    // 启用按钮
    handleSwitchChange(val, row) {
      const data = {
        userList: [
          {
            id: row.id,
            status: val,
          },
        ],
      }
      this.updateUserDataAPI({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('修改成功')
        }
      })
    },
    // 创建用户
    createUserData(payload) {
      if (payload.source === 0) {
        const data = {
          projectId: this.projectId,
          ...payload,
        }
        this.createUserDataAPI({ data }).then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('创建成功')
            this.getUserData()
            this.$refs.UsersAddDia.publicClose()
          }
        })
      } else {
        const data = {
          projectId: this.projectId,
          ...payload,
        }
        this.addProjectPersonAPI({ data }).then(res => {
          const { code } = res
          if (code === 200) {
            this.$message.success('创建成功')
            this.getUserData()
            this.$refs.UsersAddDia.publicClose()
          }
        })
      }
    },
    // 修改用户
    updateUserData(payload) {
      const data = {
        projectId: this.projectId,
        ...payload,
      }
      this.updateUserDataAPI({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('修改成功')
          this.getUserData()
          this.$refs.UsersEditDia.publicClose()
        }
      })
    },
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getUserData()
    },
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getUserData()
    },
  },
}
</script>
<style lang="scss" scoped>
.users-base-wrapper {
  height: 100%;
  background-color: $white;
  .user_main_part {
    background-color: $white;
    padding: 12px;
    .users_input {
      margin-top: 12px;
    }
    .users_button {
      margin-top: 12px;
      margin-left: 48px;
      .el-button {
        border-radius: 10%;
        margin-right: 8px;
      }
    }
    .users_table {
      margin-top: 24px;
    }
  }
}
</style>
